package com.lagou.dw.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class MaxContinuousDay extends UDF {
    // 一天的毫秒数
    private static long MILLS_FOR_DAY = 86400000L;
    // 接收一个字符串集合
    public int evaluate(List<String> dateList){
        // 如果只有一个或者空，直接返回集合长度
        if(dateList.size() <= 1){
            return dateList.size();
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ArrayList<Long> millsList = new ArrayList<>();
        for(String d: dateList){
            try {
                // 将日期字符串转化为timestamp，放入集合中
                millsList.add(formatter.parse(d).getTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        // 排序
        Collections.sort(millsList);
        // 遍历集合，寻找最长的连续天数
        int maxDay = 1;
        int tmpDay = 1;
        for(int i = 1; i < millsList.size(); i++){
            if(millsList.get(i) - millsList.get(i - 1) <= MILLS_FOR_DAY){
                tmpDay++;
            } else {
                maxDay = tmpDay > maxDay ? tmpDay : maxDay;
                tmpDay = 1;
            }
        }
        return tmpDay > maxDay ? tmpDay : maxDay;
    }

    @Test
    public void test(){
        ArrayList<String> dl = new ArrayList<>();
        dl.add("2020-01-01");
        dl.add("2020-01-02");
        dl.add("2020-01-04");
        dl.add("2020-01-07");
        dl.add("2020-01-22");
        dl.add("2020-01-09");
        dl.add("2020-01-10");
        dl.add("2020-01-11");
        dl.add("2019-12-31");
        System.out.println(evaluate(dl));
    }
}
